/*
 * 刷新表格的数据
 * @param page 页码数
 * */
var sum = 0;
var max_page;
let current = 1;
let size = 10;

function fetchUserList(page) {
    $.ajax({
        //请求地址
        url: '/user/list',
        data: { page, size },
        //success：当成功从请求地址哪里获取数据后执行的方法
        success(response) {
            // 获取后端数据库中的总数
            let count = response.count;
            sum = count;
            max_page = Math.ceil(sum / size);
            // 获取后端数据库中的列表数据
            //修改页面上总数据
            //stotal.innerHTML = count;
            viewList(response?.users || []);
        },
    });
}

function viewList(datas) {
    const html = datas.reduce((result, item) => {
        //如果用户禁用状态，则可以启用删除按钮
        const del = item.disabled ? `<b onclick="deleteUser(${item.id})" style='margin-left: 10px; color: #d43f3a'>删除</b>` : '';
        const s = item.disabled ? '<span style="color: red">禁用</span>' : '<span style="color: green">启用</span>';
        return (
            result +
            `<tr>
                <td>${item.name}</td>
                <td>${s}</td>
                <td>
                    <a href="#" style="color: #2aabd2">编辑</a>
                    ${item.disabled ? `<span onclick="enableUser(${item.id})">启用</span>` : `<span onclick="disableUser(${item.id})">禁用</span>`}
                    ${del}
                </td>
            </tr>`
        );
    }, '');
    $('#mytbody').html(html);
    $('.current-page').text(current);
    $('.total').text(max_page);
}

function enableUser(id) {
    $.ajax({
        url: '/user/enableUser',
        data: { id },
        success(res) {
            console.log(res);
            if (res) {
                reload();
                alert('启用成功');
            } else {
                alert('启用失败');
            }
        },
    });
}

function disableUser(id) {
    $.ajax({
        url: '/user/disableUser',
        data: { id },
        success(res) {
            if (res) {
                reload();
                alert('禁用成功');
            } else {
                alert('禁用失败');
            }
        },
    });
}

function deleteUser(id) {
    $.ajax({
        url: '/user/deleteUser',
        data: { id },
        success(res) {
            if (res) {
                reload();
                alert('删除成功');
            } else {
                alert('删除失败');
            }
        },
    });
}

function reload() {
    fetchUserList(current);
}

//处理点击下一页按钮
function handleNextClick() {
    if (current >= max_page) return;
    fetchUserList((current += 1));
    $('.current-page').text(current);
}
//处理点击上一页按钮
function hendleBeforeClick() {
    if (current === 1) return;
    fetchUserList((current -= 1));
    $('.current-page').text(current);
}
window.addEventListener('load', function () {
    //为Windows添加事件监听（load）,
    fetchUserList(current);
});
